package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.controller.dto.UserDto;
import com.itheima.entity.PasswordDto;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.mapper.UserMapper;
import com.itheima.mapper.UserRoleMapper;
import com.itheima.pojo.RoleMenu;
import com.itheima.pojo.User;
import com.itheima.pojo.UserRole;
import com.itheima.service.UserService;
import com.itheima.util.MD5Utils;
import com.mysql.jdbc.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.itheima.constant.MessageConstant;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description 用户服务接口实现
 * @Author makun
 * @Date 2023/9/12 16:25
 * @Version 1.0
 */
@Service
@Transactional
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserRoleMapper userRoleMapper;

    @Override
    public boolean editPasswordByUserId(Integer userId, String password) {
        User user = new User();
        user.setPassword(MD5Utils.md5(password));
        return baseMapper.update(user, new LambdaUpdateWrapper<User>().eq(User::getId, userId)) == 1;
    }

    @Override
    public boolean editOne(UserDto userDto) {
        // 编辑密码
        if (!StringUtils.isNullOrEmpty(userDto.getPassword())) {
            userDto.setPassword(MD5Utils.md5(userDto.getPassword()));
        }
        // 清空所有的角色
        userRoleMapper.delete(new LambdaQueryWrapper<UserRole>()
                .eq(UserRole::getUserId, userDto.getId()));
        // 编辑基础信息
        baseMapper.updateById(userDto);
        // 绑定角色
        for (Integer roleId : userDto.getRoleIds()) {
            userRoleMapper.insert(new UserRole(userDto.getId(), roleId));
        }
        return true;
    }

    @Override
    public boolean saveOne(UserDto userDto) {
        // 编辑密码
        if (!StringUtils.isNullOrEmpty(userDto.getPassword())) {
            userDto.setPassword(MD5Utils.md5(userDto.getPassword()));
        }
        // 添加基本信息
        baseMapper.insert(userDto);
        // 添加角色
        for (Integer roleId : userDto.getRoleIds()) {
            userRoleMapper.insert(new UserRole(userDto.getId(), roleId));
        }
        return true;
    }

    @Override
    public User login(String username, String password) {
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getUsername, username);
        userLambdaQueryWrapper.eq(User::getPassword, MD5Utils.md5(password));
        return  baseMapper.selectOne(userLambdaQueryWrapper);
    }

    @Override
    public Result updatePassword(HttpServletRequest request, PasswordDto passwordDto) {
        // 判断是否合法
        if (passwordDto.isLegal()) {
            // 获取用户对象
            User user = (User) request.getSession().getAttribute("user");
            // 更新用户密码
            user.setPassword(MD5Utils.md5(passwordDto.getPassword()));
            boolean flag = 1 == baseMapper.updateById(user);
            return new Result(flag, flag ? MessageConstant.EDIT_PASSWORD_SUCCESS : MessageConstant.EDIT_PASSWORD_FAIL);
        }

        return new Result(false, "密码不符合要求");
    }

    @Override
    public Page<User> findPage(QueryPageBean queryPageBean) {
        // 查询条件
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        String queryString = queryPageBean.getQueryString();
        if (!StringUtils.isNullOrEmpty(queryString)) {
            userLambdaQueryWrapper.like(User::getUsername, queryString)
                    .or()
                    .like(User::getTelephone, queryString);
        }
        // 分页条件
        Page<User> userPage = new Page<>(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        // 查询
        baseMapper.selectPage(userPage, userLambdaQueryWrapper);
        return userPage;
    }

    @Override
    public List<Integer> getRoleIdsByUserId(Integer userId) {
        return userRoleMapper.selectList(new LambdaQueryWrapper<UserRole>().eq(UserRole::getUserId, userId)).stream()
                .map(UserRole::getRoleId)
                .collect(Collectors.toList());
    }
}
